package cn.itcast.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.attribute.AclEntry.Builder;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieDemo04 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 1.根据用户带过来的id显示信息
		String id = request.getParameter("id");
		Book book = (Book) Db.getAll().get(id);
		out.write(book.getId() + "</br>");
		out.write(book.getName() + "</br>");
		out.write(book.getAuthor() + "</br>");
		out.write(book.getDescription() + "</br>");



		//		2. 构建cookie回写浏览器
		String cookieValue = buildCookie(id,request);

		Cookie cookie = new Cookie("bookhistory", cookieValue);
		cookie.setMaxAge(24*3600);
		cookie.setPath("/day07");
		response.addCookie(cookie);
	}

	private String buildCookie(String id, HttpServletRequest request) {
		// TODO Auto-generated method stub

		String   bookhistory = null;

		Cookie[] cookies = request.getCookies();

		for (int i = 0;cookies!=null && i < cookies.length; i++) {
			if ("bookhistory".equals(cookies[i].getName())) {
				bookhistory = cookies[i].getValue();

			}
		}

		if (bookhistory==null) {
			return id;
		}

		LinkedList<String> list = (LinkedList<String>) Arrays.asList(bookhistory.split("\\,"));
		if (list.contains(id)) {
			//bookHistory =2,5,1
			list.remove(id);


		}else{
			//bookHistory =2,5,4
			//bookHistory = 2,5
			if (list.size()>1) {
				list.removeLast();

			}

		}
		list.addFirst(id);
		StringBuffer sb = new StringBuffer();
		for (String bid : list) {

			sb.append(bid+",");

		}

		return  sb.deleteCharAt(sb.length()-1).toString();




	}





	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

